package com.yx.cloud.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.TextView;
import android.widget.Toast;

import com.aaa.async.DoneCallback;
import com.aaa.async.FailCallback;
import com.aliyun.aligeniessp_1_0.models.CheckAuthCodeBindForExtRequest;
import com.aliyun.aligeniessp_1_0.models.CheckAuthCodeBindForExtResponse;
import com.aliyun.aligeniessp_1_0.models.CheckAuthCodeBindForExtResponseBody;
import com.aliyun.alink.business.devicecenter.api.add.AddDeviceBiz;
import com.aliyun.alink.business.devicecenter.api.add.DeviceInfo;
import com.aliyun.alink.business.devicecenter.api.add.IAddDeviceListener;
import com.aliyun.alink.business.devicecenter.api.add.LinkType;
import com.aliyun.alink.business.devicecenter.api.add.ProvisionStatus;
import com.aliyun.alink.business.devicecenter.base.DCErrorCode;
import com.aliyun.alink.business.devicecenter.channel.http.IRequestCallback;
import com.aliyun.alink.business.devicecenter.provision.soundbox.channel.http.ISoundBoxProvisionRequestService;
import com.aliyun.alink.business.devicecenter.provision.soundbox.channel.http.model.request.GetAuthCodeRequest;
import com.aliyun.alink.business.devicecenter.provision.soundbox.channel.http.model.request.GetAuthResultRequest;
import com.aliyun.alink.business.devicecenter.provision.soundbox.channel.http.model.response.GetAuthResultResponse;
import com.aliyun.tea.TeaException;
import com.google.gson.Gson;
import com.iot.base.service.req.ConfigRecordSaveParam;
import com.iot.common.utils.Event;
import com.iot.common.utils.LogUtils;
import com.iot.product.sweeper.bean.Robot;
import com.iot.sweeper.AppContext;
import com.iot.sweeper.param.CleanSettingParam;
import com.yx.cloud.R;
import com.yx.cloud.base.BaseActivity;
import com.yx.cloud.bean.CreateDeviceParam;
import com.yx.cloud.constant.Constants;
import com.yx.cloud.databinding.DeviceBluetoothConnectActivityBinding;
import com.yx.cloud.network.ble.BleException;
import com.yx.cloud.network.ble.BluetoothModel;
import com.yx.cloud.network.ble.Cmd;
import com.yx.cloud.network.ble.BleProtocol;
import com.yx.cloud.product.laser.inxni.INXNIConstant;
import com.yx.cloud.product.laser.tuyapublic.BluetoothScanDeviceBean;
import com.yx.cloud.product.sdk.tmall.AliGenieSdk;
import com.yx.cloud.utils.AliHttpRequest_Runnable;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.LocationUtils;
import com.yx.cloud.utils.RomUtils;
import com.yx.cloud.utils.SharedPrefsUtil;
import com.yx.cloud.utils.StringUtils;
import com.yx.cloud.utils.ThreadUtils;
import com.yx.cloud.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * X5设备连接界面
 */
public class DeviceBluetoothConnectActivity extends BaseActivity {
    private static final String TAG = "DeviceBluetoothConnectActivity";
    private Thread thread;
    private Animation animation;
    private Message mes;
    private static com.aliyun.aligeniessp_1_0.Client client;
    private AliHttpRequest_Runnable runnable;
    private int getRobotInfo = 0;
    private int getAuthCode = 0;
    private String mTmallDeviceid = "", network, bleAddress;
    private BluetoothScanDeviceBean bluetoothData;
    private DeviceBluetoothConnectActivityBinding binding;
    private Timer timer = null;//计时器
    private TimerTask task = null;
    private int networkProgress = 0;
    private BluetoothModel model;
    private CreateDeviceParam config_bean;
    private List<Robot> newDeviceList;
    private Handler handler = new Handler() {
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int mmsg = msg.arg1;
            if (mmsg == 1) {
                stopTime();
                networkProgress = 19;
                binding.tvConnectProgress.setText(networkProgress + "");
                binding.connectLoadingStepOne.clearAnimation();
                binding.connectLoadingStepOne.setImageResource(R.mipmap.succeed_icon);
                binding.connectLoadingStepTwo.startAnimation(animation);
                binding.tvStepTwo.setTextColor(getResources().getColor(R.color.textview_color1));
                Log.i(TAG, Constants.wifi_Name + " :----bbbbbb-aaaa---> : " + Constants.wifi_Pass);
                startTime();
                //天猫配网成功后，获取扫地机信息 进行配网
                if (runnable == null) {
                    runnable = new AliHttpRequest_Runnable();
                }
                runnable.initialization("getRobot_Information", mTmallDeviceid);
            } else if (mmsg == 2) {
                if (model != null) {
                    model.disconnect();//断开蓝牙连接
                }
                Robot device = (Robot) msg.obj;
                String locations = LocationUtils.getInstance().convertAddress(DeviceBluetoothConnectActivity.this);
                ConfigRecordSaveParam param = new ConfigRecordSaveParam();
                param.setAddress(locations);
                param.setMac(device.getFirmwareInfo().getMac());
                param.setReason("BLE success");
                param.setResult("success");
                param.setSub_type(device.getProductId());
                param.setThing_name(device.getDeviceId());
                AppContext.getAccountService().configRecordSave(param);

                String name = device.getName();
                Constants.click_location = "network";
                Constants.ITEM_POSITION = -1;
                Constants.deviceVariety_id = device.getDeviceId();//保存新配网设备的id
                LogUtils.i(device.getDeviceId() + " :----bbbbbb-nnnnnnnn---> : " + Constants.deviceVariety_id);
                SharedPrefsUtil.putValue(DeviceBluetoothConnectActivity.this, Constants.DEVICEID, "deviceId", device.getDeviceId());
                SharedPrefsUtil.putValue(DeviceBluetoothConnectActivity.this, "LAST_SELECTION_ROBOT_TYPE", "last_selection_robot_type", 1);
                //切换连接设备
                AppContext.get().connectDevice(device);
                binding.connectLoadingStepTwo.clearAnimation();
                binding.connectLoadingStepTwo.setImageResource(R.mipmap.succeed_icon);
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                LogUtils.i(" :----bbbbbb-mmmmmmmmmmmmm---150 33333333333333 > : " + mTmallDeviceid);
                //TODO 配网成功后，连接上扫地机把天猫的设备id发给扫地机
                AppContext.getProductService().setDeviceCleanSettings(CleanSettingParam.newBuilder().setTmallDeviceId(mTmallDeviceid).build());
                //保存配网后的基站设备ID，用于扫地机上报没有150时
                SharedPrefsUtil.putValue(DeviceBluetoothConnectActivity.this, "TMALL_DEVICE_ID", "tamll_device_id", mTmallDeviceid);
                Intent_utils.enterIntentContext(DeviceBluetoothConnectActivity.this, ConnectSuccessActivity.class, "deviceName", name);
                finish();
            } else if (mmsg == 20) {
                int connect = msg.arg2;
                binding.tvConnectProgress.setText(connect + "");
                if (networkProgress == 19 || networkProgress == 29 || networkProgress == 34 || networkProgress == 99) {
                    stopTime();
                }
            }

        }
    };

    @Override
    public void onCreate() {
        binding = DeviceBluetoothConnectActivityBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
//        com.alibaba.ailabs.tg.utils.LogUtils.enable(true);
//        com.aliyun.alink.linksdk.tools.ALog.setLevel((byte) (0));
        if (!EventBus.getDefault().isRegistered(this)) {//加上判断
            EventBus.getDefault().register(this);
        }
        initData();
    }

    private void initData() {

        networkProgress = 0;
        startTime();//配网进度计时
        getRobotInfo = 0;
        getAuthCode = 0;
        INXNIConstant.ROTATION = true;
        network = getIntent().getStringExtra("network");
        config_bean = (CreateDeviceParam) getIntent().getSerializableExtra("config_bean");
        animation = AnimationUtils.loadAnimation(this, R.anim.ceconnect_wifi_step);
        LinearInterpolator lin = new LinearInterpolator(); //匀速
        animation.setInterpolator(lin);
        binding.connectLoadingStepOne.startAnimation(animation);
        binding.tvStepOne.setTextColor(getResources().getColor(R.color.textview_color1));

        if ("bluetooth".equals(network)) {
            //蓝牙配网
            bluetoothData = (BluetoothScanDeviceBean) getIntent().getSerializableExtra("bluetoothData");
            if (runnable == null) {
                runnable = new AliHttpRequest_Runnable();
            }
            //获取ActhCode
            runnable.initialization("getAuthCode", null);
        }

        binding.ivDeviceConnectReturn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                outConnectDialog(getString(R.string.N_Connect_Exit), "");
            }
        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        switch (event.getType()) {
            case Event.MESSAGE_TYPE_GET_ROBOT_INFO:
                //天猫精灵配网成功后获取扫地机信息,开始涂鸦蓝牙配网
                if (event.isResult()) {
                    stopTime();//停止计时
                    networkProgress = 29;
                    binding.tvConnectProgress.setText(networkProgress + "");
                    startTime();//第三段，开启计时线程
                    getRobotInfo = 201;
                    String body = (String) event.getContent();
                    JSONObject jsonString = null;
                    try {
                        jsonString = new JSONObject(body);
                        String btMac = jsonString.getString("BluetoothMac");
                        String pid = jsonString.getString("ty_pid");
                        String uuid = jsonString.getString("ty_uuid");
                        String wifimac = jsonString.getString("WifiMac");

                        boolean macCheck = StringUtils.macCheck(btMac);
                        Log.d(TAG, "network======mac地址校验 macCheck ： " + macCheck);
                        if (macCheck) {
                            stopTime();//停止计时
                            networkProgress = 34;
                            binding.tvConnectProgress.setText(networkProgress + "");
//                        ToastUtil.show(DeviceBluetoothConnectActivity.this, "获取到蓝牙mac:" + btMac + ":" + pid + ":" + uuid + ":" + wifimac, Toast.LENGTH_LONG);
                            bluetoothData.setWifiSSID(Constants.wifi_Name);
                            bluetoothData.setWifiPassWord(Constants.wifi_Pass);
                            bluetoothData.setMac(wifimac);
                            bluetoothData.setAddress(btMac);
                            bluetoothData.setUuid(uuid);
                            bluetoothData.setProductId(pid);
                            bluetoothData.setDeviceType(301);
                            startTime();//第四段，开启计时线程
                            Log.d(TAG, "network======开始涂鸦配网 :" + btMac + "," + pid + "," + uuid + "," + wifimac);
                            //TODO 这里开始进行愚公蓝牙配网
                            bleAddress = bluetoothData.getAddress();
                            connectBLE();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    String error_msg = (String) event.getContent();
                    Log.d(TAG, "network======配网失败========= 扫地机信息获取失败 ： " + error_msg);
                    //配网失败
                    getRobotInfo++;
                    if (getRobotInfo <= 200) {
                        //天猫配网成功后，获取扫地机信息 进行配网
                        Log.d(TAG, "network======配网失败========= 扫地机信息获取失败 后再取一次： ");
                        runnable.initialization("getRobot_Information", null);
                    } else {
                        //配网失败
                        Intent_utils.enterIntent(DeviceBluetoothConnectActivity.this, ConnectionFailActivity.class);
                        finish();
                    }
                }
                break;
            case Event.MESSAGE_TYPE_GET_DEVICE_LIST:
                //拿到设备列表循环比对
                if (event.isResult()) {
                    newDeviceList = (List<Robot>) event.getContent();
                    if (newDeviceList.size() > 0) {
                        for (int i = 0; i < newDeviceList.size(); i++) {
                            String deviceId = newDeviceList.get(i).getDeviceId();
                            if (deviceId.equals(config_bean.getThingname())) {
                                mQueryThing = false;
                                //配网成功 配网是否成功对比标记，在轮询中使用
                                handler.removeCallbacks(null);
                                mes = new Message();
                                mes.arg1 = 2;
                                mes.obj = newDeviceList.get(i);
                                handler.sendMessage(mes);
                            }
                        }
                    }
                }
                break;
            case Event.MESSAGE_TYPE_GET_AUTHCODE:
                //获取ActhCode
                if (event.isResult()) {
                    getAuthCode = 5;
                    //X5机型蓝牙配网
                    tmallBluetoothNetwork(bluetoothData);

                } else {
                    getAuthCode++;
                    if (getAuthCode <= 5) {
                        runnable.initialization("getAuthCode", null);
                    } else {
                        String errStr = (String) event.getContent();
                        netWorkError(errStr, "获取ActhCode失败");
                    }
                }
                break;
        }
    }

    /**
     * 阿里 蓝牙配网
     */
    private void tmallBluetoothNetwork(BluetoothScanDeviceBean bean) {

        ISoundBoxProvisionRequestService.registerRequestService(new ISoundBoxProvisionRequestService() {
            private int retryCnt = 0;

            @Override
            public void getAuthCode(GetAuthCodeRequest getAuthCodeRequest, IRequestCallback<String> iRequestCallback) {
//                Log.i(TAG, " tmallBluetoothNetwork=======> getAuthCode : 获取 AuthCode线程");
                Log.i(TAG, INXNIConstant.ALI_GENIE_AUTH_CODE + " : tmallBluetoothNetwork=======> getAuthCode : " + getAuthCodeRequest);
                iRequestCallback.onSuccess(INXNIConstant.ALI_GENIE_AUTH_CODE);
            }

            @Override
            public void getAuthResult(GetAuthResultRequest getAuthResultRequest, IRequestCallback<GetAuthResultResponse> iRequestCallback) {
                Log.i(TAG, "tmallBluetoothNetwork=======> getAuthResult ");
                pollingActivateBindings(iRequestCallback);
            }

            CheckAuthCodeBindForExtRequest.CheckAuthCodeBindForExtRequestUserInfo userInfo;
            CheckAuthCodeBindForExtRequest checkAuthCodeBindForExtRequest;
            CheckAuthCodeBindForExtResponse response;

            private void pollingActivateBindings(IRequestCallback<GetAuthResultResponse> iRequestCallback) {
                // ToastUtil.show(DeviceBluetoothConnectActivity.this, INXNIConstant.ALI_GENIE_AUTH_CODE + " : pp : " + INXNIConstant.USER_OPEN_ID, Toast.LENGTH_LONG);
                Log.i(TAG, "tmallBluetoothNetwork=======> ppppppppppppppppppppppppppp : " + INXNIConstant.USER_OPEN_ID);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (INXNIConstant.ROTATION) {
                            // Log.i(TAG, "tmallBluetoothNetwork=======> 结果轮训 pollingActivateBindingsaa");
                            try {
                                Thread.sleep(1500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            try {
                                client = AliGenieSdk.createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            userInfo = new CheckAuthCodeBindForExtRequest.CheckAuthCodeBindForExtRequestUserInfo()
                                    .setEncodeType(INXNIConstant.ENCODETYPE)
                                    .setEncodeKey(INXNIConstant.ENCODEKEY)
                                    .setIdType("OPEN_ID")
                                    .setId(INXNIConstant.USER_OPEN_ID);
                            checkAuthCodeBindForExtRequest = new CheckAuthCodeBindForExtRequest()
                                    .setAuthCode(INXNIConstant.ALI_GENIE_AUTH_CODE)
                                    .setEncodeType(INXNIConstant.ENCODETYPE)
                                    .setEncodeKey(INXNIConstant.ENCODEKEY)
                                    .setUserInfo(userInfo);
                            try {
                                response = client.checkAuthCodeBindForExt(checkAuthCodeBindForExtRequest);
                                Integer code = response.getBody().code;
                                String messageee = response.getBody().message;
//                                Log.i(TAG, "tmallBluetoothNetwork=======> 结果轮训 ff : " + response.getBody().toString());
                                Log.i(TAG, "tmallBluetoothNetwork=======> 结果轮训 aa : " + code + " : " + messageee);
                                if (code == 200 && "success".equals(messageee)) {
                                    INXNIConstant.ROTATION = false;
                                    INXNIConstant.DEVICE_ID = "";
//                                    Log.i(TAG, "tmallBluetoothNetwork=======> 结果轮训 Body() : " + new Gson().toJson(result));
                                    CheckAuthCodeBindForExtResponseBody.CheckAuthCodeBindForExtResponseBodyResultDeviceOpenInfo deviceOpenInfo = response.getBody().result.getDeviceOpenInfo();
//                                    Log.i(TAG, "tmallBluetoothNetwork=======> 结果轮训 deviceOpenInfo : " + new Gson().toJson(deviceOpenInfo));
                                    INXNIConstant.DEVICE_ID = deviceOpenInfo.id;
                                    mTmallDeviceid = deviceOpenInfo.id;
                                    Log.i(TAG, "tmallBluetoothNetwork=======> 结果轮训 成功 deviceOpenInfo.id : " + deviceOpenInfo.id);
                                    Log.i(TAG, "tmallBluetoothNetwork=======> 结果轮训 成功 NXNIConstant.DEVICE_ID : " + INXNIConstant.DEVICE_ID);
//                                    Log.i(TAG,  "tmallBluetoothNetwork=======> 结果轮训 mTmallDeviceid: " + mTmallDeviceid);
                                    iRequestCallback.onSuccess(GetAuthResultResponse.builder()
                                            .deviceId(deviceOpenInfo.id)
                                            .deviceName("soundbox")
                                            .mac(bean.getMac())
                                            .deviceProductId(32)
                                            .deviceSubModelId(32)
                                            .deviceType(deviceOpenInfo.getIdType())
                                            .build());
                                }
                            } catch (TeaException err) {
                                if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                                    Log.i(TAG, "tmallBluetoothNetwork=======1111 结果轮训 失败 : " + err.code + " : " + err.message);
                                }
                            } catch (Exception _err) {
                                TeaException err = new TeaException(_err.getMessage(), _err);
                                if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                                    Log.i(TAG, "tmallBluetoothNetwork=======2222 结果轮训 失败 : " + err.code + " : " + err.message);
                                }
                            }
                        }
                    }
                }).start();
            }
        });

        DeviceInfo deviceInfo = new DeviceInfo();
        deviceInfo.productKey = "50hs4U9Hk7vqVfJCxxt";//bean.getProductKey();50hs4U9Hk7vqVfJCxxt  xMnYQT9wEARrz2U1dIx 1gL1njXqX1ziGkwHwGE// 商家后台注册的productKey，不可为空，可以从扫描 到的DeviceInfo获取
        deviceInfo.deviceName = "";// 设备名，可为空
        deviceInfo.linkType = LinkType.ALI_GENIE_SOUND_BOX.getName();//String.valueOf(LinkType.ALI_GENIE_SOUND_BOX); "ForceAliLinkTypeNone" // 选择⾳响配⽹类型
        deviceInfo.deviceId = ""; // 新设备配⽹传空，重连则需要传⼊设备的deviceId
        deviceInfo.genieProvisionModel = 7;
        deviceInfo.userId = "-1"; // ⽤户ID
        deviceInfo.mac = bean.getMac();//"84:44:af:a1:8c:b6";bean.getMac(); // 如果⽤户指定了设备，则需要传⼊mac地址
        // 设置待添加设备的基本信息
        AddDeviceBiz.getInstance().setDevice(deviceInfo);
        // 默认配⽹超时时间为60，可以通过改接⼝变更超时时间
        AddDeviceBiz.getInstance().setProvisionTimeOut(60);
        // Log.i(TAG, "tmallBluetoothNetwork=======> deviceInfo : " + new Gson().toJson(deviceInfo));
        // 开始添加设备
        AddDeviceBiz.getInstance().startAddDevice(this, new IAddDeviceListener() {
            @Override
            public void onPreCheck(boolean b, DCErrorCode dcErrorCode) {
                // 参数检测回调
                Log.i(TAG, b + " : tmallBluetoothNetwork=======> onPreCheck : " + dcErrorCode);
            }

            @Override
            public void onProvisionPrepare(int prepareType) {
                if (prepareType == 1) {
                    // 交互引导⽤户输⼊Wi-Fi的ssid、password信息，获取到ssid、password信息
                    // 之后调⽤toggleProvision接⼝开始配⽹，参⻅第三步“输⼊账号密码”
                    AddDeviceBiz.getInstance().toggleProvision(Constants.wifi_Name, Constants.wifi_Pass, 100);
                }
                Log.i(TAG, Constants.wifi_Name + " : " + Constants.wifi_Pass + " : tmallBluetoothNetwork=======> onProvisionPrepare : " + prepareType);
            }

            @Override
            public void onProvisioning() {
                // 配⽹中
                Log.i(TAG, " : tmallBluetoothNetwork=======> onProvisioning ：配⽹中");
            }

            @Override
            public void onProvisionStatus(ProvisionStatus provisionStatus) {
                // 配⽹状态回调
                Log.i(TAG, " : tmallBluetoothNetwork=======> onProvisionStatus  " + provisionStatus.code() + " : " + provisionStatus.message());
            }

            @Override
            public void onProvisionedResult(boolean b, DeviceInfo deviceInfo, DCErrorCode errorCode) {
                Log.i(TAG, " : tmallBluetoothNetwork=======> onProvisionedResult  b: " + b);
                Log.i(TAG, " : tmallBluetoothNetwork=======> onProvisionedResult deviceInfo: " + new Gson().toJson(deviceInfo));
                Log.i(TAG, " : tmallBluetoothNetwork=======> onProvisionedResult errorCode: " + errorCode);
                if (errorCode == null) {
                    mes = new Message();
                    mes.arg1 = 1;
                    handler.sendMessage(mes);
                } else {
                    //配网超时
                    INXNIConstant.ROTATION = false;
                    Intent_utils.enterIntent(DeviceBluetoothConnectActivity.this, ConnectionFailActivity.class);
                    finish();
                }
            }
        });
    }

    private Thread queryThread;
    private int bleConnectFrequency = 0;//连接蓝牙失败次数
    private boolean mQueryThing = true;
    private int mPollingFrequency = 0;

    /**
     * 愚公蓝牙配网
     */
    private void connectBLE() {
        LogUtils.i("配网 连接 设备 address " + bleAddress);
        if (model == null) {
            model = BluetoothModel.getInstance();
        }
        model.connect(bleAddress).done(new DoneCallback<Void>() {
            @Override
            public void onDone(Void unused) {
                LogUtils.i("配网 连接 onDone");
                ToastUtil.show(DeviceBluetoothConnectActivity.this, getString(R.string.N_Connect_Ok), Toast.LENGTH_SHORT);
                String config = new Gson().toJson(config_bean);
                LogUtils.ls("配网 连接 下发给机器的数据 ：" + config);
                Cmd cmd = BleProtocol.netconfig(config);
                model.send(cmd);
                queryThread = new Thread(queryRun);
                queryThread.start();//开始轮询
            }
        }).fail(new FailCallback<BleException>() {
            @Override
            public void onFail(BleException e) {
                LogUtils.i("配网 连接 onFail");
                bleConnectFrequency++;
                if (bleConnectFrequency == 10) {
                    mQueryThing = false;
                    ToastUtil.show(DeviceBluetoothConnectActivity.this, getString(R.string.N_Connect_No), Toast.LENGTH_SHORT);
                    netWorkError("蓝牙连接失败", "愚公配网");
                } else if (bleConnectFrequency >= 0) {
                    try {
                        Thread.sleep(1500);
                    } catch (InterruptedException ex) {
                        e.printStackTrace();
                    }
                    connectBLE();
                }
            }
        });
    }

    private Runnable queryRun = new Runnable() {
        @Override
        public void run() {
            while (mQueryThing) {
                if (mPollingFrequency < 40) {
                    mPollingFrequency++;
                    try {
                        Thread.sleep(5000);
                        LogUtils.i("配网 开启轮询----------");
                        AppContext.getAccountService().getDeviceList();//轮询配网结果
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    mQueryThing = false;
                    netWorkError(getString(R.string.N_Connect_No), "愚公配网超时");
                }
            }
        }
    };

    private void outConnectDialog(String dialogTitle, String content) {
        Dialog dialog = new Dialog(DeviceBluetoothConnectActivity.this);
        dialog.setContentView(R.layout.outlogin_dialog);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.setCanceledOnTouchOutside(false);
        TextView mBtnOutLoginConfirm = dialog.findViewById(R.id.btn_outLoginConfirm);
        TextView mBtnOutLoginCancel = dialog.findViewById(R.id.btn_outLoginCancel);
        TextView mTvDialogTitle = dialog.findViewById(R.id.tv_dialogTitle);
        TextView mContent = dialog.findViewById(R.id.tv_content);

        mTvDialogTitle.setText(dialogTitle);
        mContent.setText(content);
        mBtnOutLoginConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                INXNIConstant.ROTATION = false;
                AddDeviceBiz.getInstance().stopAddDevice();
                stopTime();
                ToastUtil.show(DeviceBluetoothConnectActivity.this, "取消配网", Toast.LENGTH_SHORT);
                Log.i(TAG, " :----bbbbbb- 取消配网---> : ");
                if ("bluetooth".equals(network)) {
                    String uuid = bluetoothData.getUuid();
                    if (uuid != null) {
//                        AppContext.getService().stopBluetoothConfig(bluetoothData);
                    }
                    if (model != null) {
                        model.disconnect();//断开蓝牙连接
                    }
                }
                dialog.dismiss();
                if (EventBus.getDefault().isRegistered(this)) {
                    EventBus.getDefault().unregister(this);
                }
                Intent_utils.backIntent(DeviceBluetoothConnectActivity.this);
            }
        });
        mBtnOutLoginCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void netWorkError(String src, String source) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (model != null) {
                    model.disconnect();//断开蓝牙连接
                }
                binding.connectLoadingStepOne.clearAnimation();
                binding.connectLoadingStepOne.setImageResource(R.mipmap.nonsupport_icon);
                binding.connectLoadingStepTwo.clearAnimation();
                binding.connectLoadingStepTwo.setImageResource(R.mipmap.nonsupport_icon);
                binding.lottieAnimationView.clearAnimation();
                ToastUtil.show(DeviceBluetoothConnectActivity.this, src, Toast.LENGTH_SHORT);
                String locations = LocationUtils.getInstance().convertAddress(DeviceBluetoothConnectActivity.this);
                ConfigRecordSaveParam param = new ConfigRecordSaveParam();
                param.setAddress(locations);
                param.setMac("");
                param.setThing_name(config_bean.getThingname());//getThingname
                param.setReason("BLE " + src);
                param.setResult("fail");
                param.setSub_type(config_bean.getDevice_type());//getDevice_type
                AppContext.getAccountService().configRecordSave(param);
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Log.d(TAG, "netWorkError==错误来源============= " + src + " , " + source);
                //配网失败
                Intent_utils.enterIntent(DeviceBluetoothConnectActivity.this, ConnectionFailActivity.class);
                finish();
            }
        });
    }

    //启动
    private void startTime() {
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                //此处自己设置
                networkProgress++;
                mes = new Message();
                mes.arg1 = 20;
                mes.arg2 = networkProgress;
                handler.sendMessage(mes);
                //Log.i(TAG, "开始计时 :" + networkProgress);
            }
        };
        timer.schedule(task, 0, 200);//第二段，开启计时线程
    }

    //关闭
    private void stopTime() {
        if (timer != null) {
            timer.cancel();
            timer = null;//据说这样不会自动跳出软件
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy===============");
        stopTime();
        if (model != null) {
            model.disconnect();
        }
        bleConnectFrequency = -1;
        getRobotInfo = 200;
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if (thread != null) {
            thread.interrupt();
        }
        if (runnable != null) {
            ThreadUtils.getInstance().removeThread(runnable);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Log.d(TAG, "onKeyDown ===============");
            outConnectDialog(getString(R.string.N_Connect_Exit), "");
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
